package com.flink.examples.redis;

import org.apache.commons.lang3.RandomUtils;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.redis.RedisSink;
import org.apache.flink.streaming.connectors.redis.common.config.FlinkJedisPoolConfig;
import org.apache.flink.streaming.connectors.redis.common.mapper.RedisCommand;
import org.apache.flink.streaming.connectors.redis.common.mapper.RedisCommandDescription;
import org.apache.flink.streaming.connectors.redis.common.mapper.RedisMapper;

/**
 * @Description 将数据流写入到redis中
 * @Author JL
 * @Date 2020/09/18
 * @Version V1.0
 */
public class DataStreamSink {

    /**
     * 官方文档：https://bahir.apache.org/docs/flink/current/flink-streaming-redis/
     */

    public static void main(String[] args) throws Exception {
        final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //1.写入数据到流中
        String [] words = new String[]{"props","student","build","name","execute"};
        DataStream<Tuple2<String, Integer>> sourceStream = env.fromElements(words).map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String v) throws Exception {
                return Tuple2.of(v, RandomUtils.nextInt(1000, 9999));
            }
        });
        sourceStream.print();

        //2.实例化FlinkJedisPoolConfig 配置redis
        FlinkJedisPoolConfig conf = new FlinkJedisPoolConfig.Builder().setHost("127.0.0.1").setPort(6379).build();

        //3.写入到redis，实例化RedisSink，并通过flink的addSink的方式将flink计算的结果插入到redis
        sourceStream.addSink(new RedisSink<>(conf, new RedisMapper<Tuple2<String, Integer>>(){
            @Override
            public RedisCommandDescription getCommandDescription() {
                return new RedisCommandDescription(RedisCommand.SET, null);
                //通过实例化传参，设置hash值的key
                //return new RedisCommandDescription(RedisCommand.HSET, key);
            }
            @Override
            public String getKeyFromData(Tuple2<String, Integer> tuple2) {
                return tuple2.f0;
            }
            @Override
            public String getValueFromData(Tuple2<String, Integer> tuple2) {
                return tuple2.f1.toString();
            }
        }));
        env.execute("flink redis sink");
    }

}
